package com.mentaleye.biz.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mentaleye.bean.StudentPunchRecordBean;
import com.mentaleye.bean.WorkTimeBean;
import com.mentaleye.biz.StudentPunchRecordBiz;
import com.mentaleye.biz.TaskDateBiz;
import com.mentaleye.biz.WorkTimeBiz;
import com.mentaleye.dal.model.StudentAttendanceRecord;
import com.mentaleye.dal.model.StudentDiscipline;
import com.mentaleye.dal.model.StudentDisciplineRecord;
import com.mentaleye.dal.model.StudentPunchRecord;
import com.mentaleye.service.StudentAttendanceRecordService;
import com.mentaleye.service.StudentDisciplineRecordService;
import com.mentaleye.service.StudentDisciplineService;
import com.mentaleye.service.StudentPunchRecordService;
import com.mentaleye.util.CommonPage;
import com.mentaleye.util.CommonResult;
import com.mentaleye.util.DateFormatter;
import com.mentaleye.util.ExcelInputUtil;
import com.mentaleye.util.ObjectUtil;
import com.mentaleye.util.PunchDataUtil;
import com.mentaleye.util.AttendanceDataUtil;

@Service
public class StudentPunchRecordBizImpl implements StudentPunchRecordBiz {

	private static Logger logger = Logger.getLogger(StudentPunchRecordBiz.class);

	@Autowired
	private StudentAttendanceRecordService attendanceRecordService;

	@Autowired
	private StudentPunchRecordService punchRecordService;

	@Autowired
	private StudentDisciplineService disciplineService;

	@Autowired
	private StudentDisciplineRecordService disciplineRecordService;

	@Autowired
	private TaskDateBiz taskDateBiz;

	@Autowired
	private WorkTimeBiz workTimeBiz;

	@Override
	public CommonResult updateRecord(StudentPunchRecordBean punchRecordBean) {
		CommonResult result = new CommonResult();
		try {
			punchRecordBean.setWriteTime(DateFormatter.parse(punchRecordBean.getWriteTimeStr(), "yyyy-MM"));
			StudentPunchRecord record = (StudentPunchRecord) ObjectUtil.transfer(punchRecordBean,
					StudentPunchRecord.class);
			if (this.punchRecordService.updateRecord(record)) {
				result.setIsSuccess(true);
				result.setResultMsg("更新成功！");
			} else {
				result.setResultMsg("更新失败！");
			}
		} catch (Exception e) {
			result.setResultMsg("更新异常！");
			logger.error("学生打卡信息更新异常！", e);
		}
		return result;
	}

	@Override
	public CommonResult updateByList(List<StudentPunchRecord> recordList) {
		CommonResult result = new CommonResult();
		try {
			if (!recordList.isEmpty()) {
				Date writeTime = recordList.get(0).getWriteTime();
				if (this.punchRecordService.deleteByWriteTime(writeTime)) {
					if (this.punchRecordService.insertByList(recordList)) {
						result.setIsSuccess(true);
						result.setResultMsg("更新成功！");
					} else {
						result.setResultMsg("更新失败！");
					}
				} else {
					result.setResultMsg("更新失败！");
				}
			}
		} catch (Exception e) {
			result.setResultMsg("更新异常！");
			logger.error("学生打卡信息更新异常！", e);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public CommonResult updateByFile(String fileName, HttpServletRequest request) {
		CommonResult result = new CommonResult();
		String uploadPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/");
		String filePath = uploadPath + "\\" + fileName;
		Date writeTime = null;
		List<StudentPunchRecord> punchRecordListInput =null;
		List<StudentDiscipline> disciplineList=null;
		List<StudentDisciplineRecord> disciplineRecordList =null;
		List<Date> workDateList=null;
		List<StudentPunchRecord> punchRecordList=null;
		try {
			punchRecordListInput = ExcelInputUtil.getExcelData(filePath);
			if (!punchRecordListInput.isEmpty()) {
				writeTime = punchRecordListInput.get(0).getWriteTime();
				String yearMonth = DateFormatter.format(writeTime, "yyyy-MM");
				int index = yearMonth.indexOf("-");
				String year = yearMonth.substring(0, index);
				String month = yearMonth.substring(index + 1, yearMonth.length());
				workDateList = this.taskDateBiz.getWorkDateByOneMouth(year, month, true);
				punchRecordList = PunchDataUtil.getPunchListByInputAndWorkTimeList(punchRecordListInput, workDateList);
				float requireNum = workDateList.size();
				WorkTimeBean workTimeBean = this.workTimeBiz.queryWorktimeByMonth(yearMonth);
				disciplineList = this.disciplineService.getList();
				this.disciplineRecordService.deleteBySelective(writeTime);
				disciplineRecordList = this.disciplineRecordService.getList();
				Map<String, Object> resultMap = AttendanceDataUtil.getAttendanceListByList(requireNum,punchRecordList, 
						disciplineList, disciplineRecordList, workTimeBean);
				List<StudentAttendanceRecord> attendanceRecordList = (List<StudentAttendanceRecord>) resultMap.get("recordList");
				List<StudentDisciplineRecord> dRRecordList = (List<StudentDisciplineRecord>) resultMap.get("dRRecordList");
				if(!dRRecordList.isEmpty()){
					this.disciplineRecordService.insertByList(dRRecordList);
				}
				this.punchRecordService.deleteByWriteTime(writeTime);
				if (this.punchRecordService.insertByList(punchRecordList)) {
					if (!attendanceRecordList.isEmpty()) {
						this.attendanceRecordService.deleteByWriteTime(writeTime);
						if (this.attendanceRecordService.insertByList(attendanceRecordList)) {
							result.setIsSuccess(true);
							result.setResultMsg("更新成功！");
						} else {
							result.setResultMsg("更新失败！");
						}
					} else {
						result.setResultMsg("更新失败！");
					}
				} else {
					result.setResultMsg("更新失败！");
				}
			} else {
				result.setResultMsg("更新失败！");
			}
		} catch (Exception e) {
			result.setResultMsg("更新异常！");
			logger.error("学生打卡信息更新异常！", e);
		}

		return result;
	}

	@Override
	public void getListByPage(CommonPage page) {
		List<Map<String, Object>> recordList = null;
		try {
			recordList = this.punchRecordService.getListByMap(page.pageToMap());
			page.setPageData(recordList);
		} catch (Exception e) {
			logger.error("分页读取学生打卡信息异常！", e);
		}
	}

	@Override
	public Map<String, Object> getBeanByKey(Long recordId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Map<String, Object> recordBean = null;
		try {
			paramMap.put("recordId", recordId);
			List<Map<String, Object>> mapList = this.punchRecordService.getListByMap(paramMap);
			if (!mapList.isEmpty()) {
				recordBean = mapList.get(0);
			}
		} catch (Exception e) {
			logger.error("查询学生打卡记录异常！", e);
		}
		return recordBean;
	}

	@Override
	public List<StudentPunchRecord> getListBySelective(StudentPunchRecordBean recordBean) {
		List<StudentPunchRecord> recordList = null;
		try {
			recordList = this.punchRecordService.getListBySelective(recordBean.getStudentId(),
					recordBean.getWriteTime());
		} catch (Exception e) {
			logger.error("查询学生打卡记录异常！", e);
		}
		return recordList;
	}

	@Override
	public StudentPunchRecordBean getBeanBySelective(StudentPunchRecordBean recordBean) {
		List<StudentPunchRecord> recordList = null;
		try {
			recordList = this.punchRecordService.getListBySelective(recordBean.getStudentId(),
					recordBean.getWriteTime());
			if (recordList.isEmpty()) {
				recordBean = new StudentPunchRecordBean();
			} else {
				recordBean = (StudentPunchRecordBean) ObjectUtil.transfer(recordList.get(0),
						StudentPunchRecordBean.class);
			}
		} catch (Exception e) {
			logger.error("查询学生打卡记录异常！", e);
		}
		return recordBean;
	}
}
